import request from '@/utils/request';
import axios from 'axios';
import { IRequestGetAnswer, IModelInfo, IUserConfiguredModelInfo, IRequestSetModel, IRequestDeleteModel } from './ai';

const basePath = '/api/aiProxy/v1';

/**
 * 获取支持的模型列表
 * @returns {Promise} 返回支持的模型列表
 */
export function getModelList(): Promise<IModelInfo[]> {
  return request({
    url: `${basePath}/model/list`,
    method: 'POST',
  }) as any as Promise<IModelInfo[]>;
}

/**
 * 获取已配置的模型信息列表
 * @returns {Promise} 返回已设置的模型信息列表
 */
export function getConfiguredModelList(): Promise<IUserConfiguredModelInfo[]> {
  return request({
    url: `${basePath}/model/list/self`,
    method: 'post',
  }) as any as Promise<IUserConfiguredModelInfo[]>;
}

export function saveConfiguredModelKey(data: IRequestSetModel) {
  return request({
    url: `${basePath}/apiKey/setting`,
    method: 'post',
    data,
  });
}

export function deleteConfiguredModelKey(data: IRequestDeleteModel) {
  return request({
    url: `${basePath}/apiKey/remove`,
    method: 'post',
    data,
  });
}

/**
 * 获取回答
 * @param {IRequestGetAnswer} data 获取回答请求参数
 * @param {Function} streamCb 流回调
 * @returns {Promise} 返回请求对象
 */
export function getAnswer(data: IRequestGetAnswer, streamCb?: (reps: any) => void) {
  const { CancelToken } = axios;
  const source = CancelToken.source();
  const req = request({
    url: `${basePath}/model/answerInStream`,
    method: 'post',
    data,
    cancelToken: source.token,
    onDownloadProgress(event) {
      const responseText = event?.target?.responseText || '';
      const lines = responseText.split('\n').filter((i: string) => i);
      const lastLine = lines.pop();
      let lastResp = null;
      try {
        lastResp = JSON.parse(lastLine);
      } catch (err) {
        console.log('parse resp error ', err);
      }
      streamCb(lastResp);
    },
  });
  return {
    request: req,
    source,
  };
}
